<template>
  <div class="contents">
    <el-form :inline="true" :model="dataFilter" class="demo-form-inline">
      <el-form-item label="活动状态：">
        <el-select v-model="dataFilter.userState" @change="pagingQuery">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="优惠类型">
        <el-select v-model="dataFilter.type" @change="pagingQuery">
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="搜索：">
        <el-input v-model="dataFilter.name" placeholder="优惠券名称"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="pagingQuery">查询</el-button>
      </el-form-item>
    </el-form>
    <el-button @click="GoToAdd">新增</el-button>
    <el-table :data="table1.list" style="width: 100%; margin-top: 8px">
      <el-table-column label="优惠券名称" prop="name" width="150" />
      <el-table-column label="类型" prop="type" width="150" />
      <el-table-column label="发放方式" prop="sendMethod" width="150" />
      <el-table-column label="面值" prop="faceValue" width="150" />
      <el-table-column label="有效期" prop="effectTime" width="150" />
      <el-table-column label="领取限制" prop="limit" width="150" />
      <el-table-column label="使用门槛" prop="useThreshold" width="150" />
      <el-table-column label="可用数量" prop="userQuantity" width="150" />
      <el-table-column label="已使用/领取" prop="" width="150" />
      <el-table-column label="发放时间" prop="" width="150" />
      <el-table-column label="状态" width="150">
        <template slot-scope="scope">
          <span :class="scope.row.userState === 1 ? 'specialColor' : ''">
            {{ scope.row.userState === 0 ? '已关闭' : '进行中' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="230" fixed="right">
        <template slot-scope="scope">
          <div style="display: flex">
            <div>
              <el-button
                style="margin-right: 15px"
                @click="detailsRow(scope.$index, scope.row)"
                type="text"
                size="small"
              >
                详情
              </el-button>
            </div>
            <div v-show="scope.row.userState === 0 ? false : true">
              <el-button
                style="margin-right: 15px"
                @click="editRow(scope.$index, scope.row)"
                type="text"
                size="small"
              >
                编辑
              </el-button>
            </div>
            <div>
              <el-button
                style="margin-right: 15px"
                @click.native.prevent="deleteRow(scope.$index, scope.row)"
                type="text"
                size="small"
              >
                领取记录
              </el-button>
            </div>
            <div
              style="margin-top: 4px"
              v-show="scope.row.userState === 0 ? false : true"
            >
              <el-dropdown>
                <span
                  class="el-dropdown-link"
                  style="font-size: 12px; cursor: pointer; color: #1890ff"
                >
                  更多
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item
                    @click.native="getAllProfiles(scope.$index, scope.row)"
                  >
                    手动发放
                  </el-dropdown-item>
                  <el-dropdown-item @click.native="stopActive">
                    终止活动
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </div>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="total, prev, pager, next,sizes"
      :page-sizes="[5, 10, 20, 30, 40]"
      style="text-align: right"
      :current-page="dataFilter.pageSize"
      :total="total"
      :page-size="dataFilter.pages"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!--  手动发放dialog -->
    <el-dialog
      title="发放优惠券"
      :visible.sync="handleSentDialogVisible"
      width="72%"
      height="500px"
    >
      <!-- 表单 -->
      <el-form
        :inline="true"
        :model="customerInfoQuery"
        class="demo-form-inline"
      >
        <el-form-item>
          <el-select
            v-model="customerInfoQuery.formHandleSent"
            placeholder="选择客户类型"
            style="margin-right: 5px; width: 170px"
          >
            <el-option
              v-for="item in customerTypeOptions"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="customerInfoQuery.AreaName"
            placeholder="选择区域"
            style="margin-right: 5px; width: 170px"
          >
            <el-option
              v-for="item in areaOptions"
              :key="item.value"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="orderSituationsOptions"
            placeholder="下单情况"
            style="margin-right: 5px; width: 170px"
          >
            <el-option
              v-for="item in orderSituation"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="customerInfoQuery.serch"
            placeholder="请输入客户名称/编码进行搜索"
            style="width: 210px"
          ></el-input>
          <el-button
            type="primary"
            icon="el-icon-search"
            style="border: 0; height: 31px; margin-left: -2px; margin-top: -1px"
          ></el-button>
        </el-form-item>
        <el-button
          type="primary"
          style="margin-left: 40px"
          @click="dialogSentClient = true"
        >
          发放筛选客户
        </el-button>
        <el-form-item>
          <div style="margin-left: 20px; margin-top: -16px">
            <p style="font-size: 13px; line-height: 13px">
              已选择:{{ this.checkBox }}项
            </p>
            <p style="font-size: 13px; line-height: 13px">剩余数量:</p>
          </div>
        </el-form-item>
      </el-form>
      <!-- 发放优惠券table表格 -->
      <el-table
        ref="multipleTable"
        :data="handleSentTableData"
        tooltip-effect="dark"
        style="width: 100%"
        @select="selectData"
        @select-all="selectData"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column
          label="客户名称"
          width="250"
          prop="name"
        ></el-table-column>
        <el-table-column
          prop="account"
          label="联系手机"
          width="250"
        ></el-table-column>
        <el-table-column
          prop="categoryId"
          label="客户类型"
          width="250"
        ></el-table-column>
        <el-table-column
          prop="customerAddress.areaId"
          label="区域"
          width="250"
        ></el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        background
        style="text-align: right"
        layout="total, prev, pager, next,sizes,jumper"
        :page-sizes="[5, 10, 20, 30, 40]"
        :total="total02"
        :current-page="profilesData.currentPage"
        :page-size="profilesData.count"
        @size-change="sentSize"
        @current-change="sentCurrent"
      />

      <span slot="footer" class="dialog-footer">
        <el-button @click="handleSentDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureSent">确定发放</el-button>
      </span>
    </el-dialog>
    <!-- 发放筛选客户dialog -->
    <el-dialog
      title="每个客户发放数量"
      :visible.sync="dialogSentClient"
      width="20%"
      height="160px"
      style="margin-top: 110px"
    >
      <el-input type="number" v-model="inputValue" @input="limitNum"></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogSentClient = false">取 消</el-button>
        <el-button type="primary" @click="dialogSentClient = false">
          确 定
        </el-button>
      </span>
    </el-dialog>
    <!-- 领取记录抽屉 -->
    <el-drawer
      title="领取详情"
      :visible.sync="drawer"
      direction="rtl"
      :before-close="handleClose"
      size="65%"
    >
      <div style="margin-left: 20px">
        搜索：
        <el-input
          v-model="recordDataFilter.customerName"
          placeholder="请输入客户名称编码"
          style="width: 250px"
        ></el-input>
        <el-button type="primary" style="height: 34px; margin-left: 15px" @click="record">
          查询
        </el-button>
        <el-button style="height: 34px">导出</el-button>
      </div>
      <template>
        <el-table :data="recordTableData" style="width: 100%; margin-top: 30px">
          <el-table-column
            prop="marketingCoupon.name"
            label="优惠券名称"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="customerInfo.name"
            label="客户"
            width="180"
          ></el-table-column>
          <el-table-column
            prop="marketingCoupon.faceValue"
            label="面值"
          ></el-table-column>
          <el-table-column
            prop="marketingCoupon.createtime"
            label="创建时间"
          ></el-table-column>
          <el-table-column prop="ctime" label="领取时间"></el-table-column>
          <el-table-column prop="usetime" label="使用时间"></el-table-column>
          <el-table-column prop="orderNo" label="使用订单"></el-table-column>
          <el-table-column prop="address" label="状态"></el-table-column>
          <el-table-column prop="address" label="操作"></el-table-column>
        </el-table>
      </template>
      <!-- 分页 -->
      <el-pagination
        background
        style="text-align: right"
        layout="total, prev, pager, next,sizes"
        :total="totalOfRecord"
        :current-page="recordDataFilter.current"
        :page-size="recordDataFilter.pagesize"
        @size-change="recordSizeChange"
        @current-change="recordCurrentChange"
      />
    </el-drawer>
    <el-dialog :visible.sync="TerminationActivities" width="25%" height="360px">
      <!-- 自定义title -->
      <div slot="title" class="header-title">
        <span class="title-text">
          <i class="el-icon-warning" style="color: rgb(255, 159, 0)"></i>
          <span
            style="color: rgb(0 0 0 / 85%); font-weight: bold; margin-left: 5px"
          >
            确认
          </span>
        </span>
      </div>
      <span style="font-size: 12px; margin-left: 21.5px; padding: 0px">
        确认终止活动 ？
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="TerminationActivities = false">取 消</el-button>
        <el-button type="primary" @click="sureClickStopActivities">
          确 定
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getLists,
  edit,
  close,
  getAllAreaList,
  sentConponlist,
  receiveRecord,
} from '@/api/marketing/couponList'
import {
  getAllProfileType,
  getAllGroup,
  getList,
} from '@/api/customer/customerProfile'
import { checkAreaId } from '@/api/distribution/lineArea'

export default {
  data() {
    return {
      formData: {},
      table1: [],
      //普通查询。
      dataFilter: {
        pagesize: 10,
        current: 1,
        id: 1,
        name: '',
        type: null,
        sendMethod: '',
        faceValue: null,
        effectTime: null,
        limit: '',
        useThreshold: '',
        userQuantity: null,
        userState: 0,
        cuser: '',
        ctime: null,
        uuser: '',
        utime: null,
        createtime: '',
        closetime: '',
      },

      profilesData: {
        currentPage: 1,
        count: 5,
      },
      customerInfoQuery: {
        formHandleSent: null,
      },
      handleSentTableData: [], //手动发放优惠券。
      total: 0, //总数。
      total02: 0,
      totalOfRecord: 0,
      drawer: false,
      currentPage: 1,
      count: 10,
      recordTableData: [], //记录tableData。
      handleSentDialogVisible: false, //手动发放dialog。
      TerminationActivities: false,
      customerTypeOptions: [],
      areaOptions: [],
      orderSituationsOptions: [],
      checkBox: 0,
      dialogSentClient: false,
      inputValue: 1,
      //发放优惠券所传入的对象。
      list: {
        marketingCouponCustomerItemsList: [],
      },
      cid: '',
      recordDataFilter: {
        pagesize: 10,
        current: 1,
        couponId: '',
        customerId: '',
        customerName: '',
      },
      TerminationData: {},
      statusOptions: [
        {
          value: 0,
          label: '未使用',
        },
        {
          value: 1,
          label: '已使用',
        },
      ],
      typeOptions: [
        {
          value: null,
          label: '全部',
        },
        {
          value: 0,
          label: '新人券',
        },
        {
          value: 1,
          label: '普通券',
        },
      ],
      orderSituation: [
        { value: 2, label: '全部' },
        {
          value: 0,
          label: '从未下单',
        },
        {
          value: 1,
          label: '已下过单',
        },
      ],
    }
  },
  async created() {
    await this.pagingQuery()
    await this.ProfileType()
    await this.AllArea()
    // await this.getAreaName()
  },
  methods: {
    async pagingQuery() {
      this.listLoading = true
      const res = await getLists(this.dataFilter)
      this.table1 = res
      this.total = res.total
    },
    async ProfileType() {
      const res = await getAllProfileType()
      this.customerTypeOptions = res.data
    },
    async AllArea() {
      const res = await getAllAreaList()
      this.areaOptions = res.data
    },
    //领取记录GetList。
    async record() {
      const res = await receiveRecord(this.recordDataFilter)
      this.recordTableData = res.list
      this.totalOfRecord = res.total
    },
    //分页点击事件。
    recordSizeChange(val) {
      this.recordDataFilter.pagesize = val
      this.record()
    },
    //分页点击事件。
    recordCurrentChange(val) {
      this.recordDataFilter.current = val
      this.record()
    },
    //分页点击事件。
    handleSizeChange(val) {
      this.dataFilter.pagesize = val
      this.pagingQuery()
    },
    //分页点击事件。
    handleCurrentChange(val) {
      this.dataFilter.current = val
      this.pagingQuery()
    },
    //分页点击事件。（手动发放优惠卷）
    sentSize(val) {
      this.profilesData.count = val
      this.getAllProfiles()
    },
    //分页点击事件。（手动发放优惠卷）
    sentCurrent(val) {
      this.profilesData.currentPage = val
      this.getAllProfiles()
    },
    //form详情。
    detailsRow(index, item) {
      this.$router.push({
        path: '/market/campaign/couponListAdd',
        query: { item, flag: 'details', toDisableTable: true, back: false },
      })
    },
    //form编辑。
    editRow(index, item) {
      this.$router.push({
        path: '/market/campaign/couponListEdit',
        query: { item, flag: 'edit', showSubmit: true },
      })
    },
    //优惠卷新增按钮。
    GoToAdd() {
      this.$router.push({
        path: '/market/campaign/couponListAdd',
        // query: { flag: 'add', showSubmit: true },
      })
    },
    //click领取记录。
    deleteRow(index, data) {
      this.drawer = true
      this.recordDataFilter.couponId = data.id
      this.record()
    },
    //click终止活动。
    stopActive(data) {
      this.TerminationActivities = true
      this.TerminationData = data //这里因为局部作用域的作用，故将data赋值给‘全局变量’TerminationData。
      console.log(this.TerminationData)
    },
    //click终止活动确认按钮。
    async sureClickStopActivities() {
      this.editForm = this.TerminationData
      this.editForm.userState = 0
      const res = await close(this.editForm)
      if (res.status == 200) {
        this.TerminationActivities = false
        this.$message.success('终止成功')
      } else {
        this.TerminationActivities = false
        this.$message.error('终止失败')
      }
      this.pagingQuery()
    },
    //关闭抽屉
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },
    //手动发放的点击事件：
    async getAllProfiles(index, row) {
      this.handleSentDialogVisible = true
      console.log(row, '获取当前行的优惠券ID')
      this.cid = row.id
      const res = await getList(
        this.profilesData.currentPage,
        this.profilesData.count
      )
      this.total02 = res.data.list.length
      this.handleSentTableData = res.data.list.map((e) => {
        this.getAreaName(e.customerAddress.areaId, (data) => {
          e.customerAddress.areaId = data
        })
        console.log(e, e.customerAddress.areaId)
        return e
      })
    },
    //多选表格的多选触发：
    selectData(info) {
      info.forEach((element) => {
        console.log(element, '循环所遍历出来的数据')
        let Object01 = {
          customerId: element.id,
          couponId: this.cid,
        }
        this.list.marketingCouponCustomerItemsList.push(Object01)
      })
      this.checkBox = info.length
      console.log(
        this.list.marketingCouponCustomerItemsList,
        'this.list.marketingCouponCustomerItemsList---发放优惠券需传入的对象'
      )
      //数组去重。
      let newobj = {}
      let Array = this.list.marketingCouponCustomerItemsList.reduce(
        (total, currentValue) => {
          newobj[currentValue.customerId]
            ? ''
            : (newobj[currentValue.customerId] = total.push(currentValue))
          return total
        },
        []
      )
      console.log(Array, 'Array---数组去重后得到的结果')
      this.list.marketingCouponCustomerItemsList = Array
    },
    //通过区域id查询区域。
    async getAreaName(e, callback) {
      const res = await checkAreaId(e)
      callback(res.data.name)
    },
    //确定发放按钮。
    async sureSent() {
      this.handleSentDialogVisible = false
      const result = await sentConponlist(this.list)
    },

    //输入限制。
    limitNum() {
      if (this.inputValue > 99) {
        this.inputValue = 99
      } else if (this.inputValue < 1) {
        this.inputValue = 1
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.contents {
  padding: 10px 20px;
}
::v-deep header#el-drawer__title {
  height: 46px;
  font-size: 19px;
  font-weight: bold;
  border-bottom: 1px solid rgb(232 232 232);
}
::v-deep header#el-drawer__title {
  padding-top: 0;
}
::v-deep .el-dialog__header {
  border-bottom: 1px solid rgb(240 242 240);
  font-size: 14px;
}
::v-deep span.el-pagination__jump {
  margin-left: 0;
}
.specialColor {
  color: rgb(255, 159, 0);
}
::v-deep [data-v-e77b6126] .el-dialog__header {
  border-bottom: none;
  font-size: 14px;
}
::v-deep .el-dialog__body {
  padding: 0 20px;
}
::v-deep .el-dialog__title {
  line-height: 24px;
  font-size: 14px;
  color: rgb(48 49 51);
}
</style>
